<template>
    <div class="chat-container">
        <div class="chat-list">
            <ul>
                <li v-for="(user, index) in userList" :key="index" @click="selectUser(user)"
                    :class="{ 'selected': user === selectedUser }">
                    {{ user.toUser }}
                    <p v-if="user.unread === 1" style="color: red">未读</p>
                    <span class="delete-icon" @click.stop="deleteUser(user)">
                        <i class="el-icon-delete"></i>
                    </span>
                </li>
                <li v-if="userList.length <1">暂无消息</li>
            </ul>
        </div>
        <div class="chat-window">
            <div class="chat-content" ref="scrollContainer">
                <ul>
                    <li v-for="(message, index) in fromUserMsg" :key="index">
                        <div class="message" :class="{ 'sent': message.sent, 'received': !message.sent }">
                            <div class="message-content">
                                <p v-if="message.type === 'text'">{{ message.content }}</p>
                                <img v-if="message.type === 'image'" :src="message.content" alt="Image"/>
                            </div>
                        </div>
                    </li>
                </ul>
            </div>
            <div class="chat-input">
                <input v-model="inputMessage" placeholder="Type your message..."/>
                <button @click="sendMessage">Send</button>
            </div>
        </div>
    </div>
</template>

<script>
    import {getNickName, getToken} from "@/utils/setToken";
    import axios from "axios";

    export default {
        data() {
            return {
                userList: [],
                fromUserMsg: [{source: '', content: "", type: "", sent: false}],
                inputMessage: '',
                toUser: '',
                linkId: '',
                fromUser: '',
                websocket: null,
                selectedUser: null,
                timer: null,
                memberName: '',
            };
        },
        mounted: function () {
            this.fromUser = getNickName();
            this.memberName = getNickName();
            this.toUser = sessionStorage.getItem("merchantName");
            this.initMsg();
            this.initUserList();
        },
        methods: {

            scrollToBottom() {
                const container = this.$refs.scrollContainer;
                container.scrollTop = container.scrollHeight;
            },
            initMsg() {
                axios({
                    url: '/api/chat/chat/getMsg',
                    method: 'get',
                    params: {
                        fromUser: this.fromUser,
                        toUser: this.toUser,
                        currentIndex: 10,
                    }
                }).then(res => {
                    console.log(res.data)
                    this.fromUserMsg = res.data;
                })
            },
            initUserList() {
                axios({
                    url: '/api/chat/chat/getUserList',
                    method: 'get',
                    params: {
                        username: this.fromUser
                    }
                }).then(res => {
                    this.userList = res.data;
                    let isExist = false;
                    this.userList.find(item => {
                        if (item.toUser === this.toUser) {
                            this.selectedUser = item;
                            isExist = true;
                        }
                    })
                    if (!isExist) {
                        let user = {
                            toUser: this.toUser,
                            unread: 0
                        }
                        this.userList.push(user)
                        this.selectedUser = user;
                    }
                    this.initMsg();
                    this.getWebsocket();
                })
            },
            selectUser(user) {
                if (this.websocket != null) {
                    this.websocket.close();
                }
                this.selectedUser = user;
                this.userList.find(item => {
                    if (item.toUser === this.toUser) {
                        item.unread = 0;
                    }
                });
                this.toUser = user.toUser;
                this.initMsg();
                this.getWebsocket();
            },
            sendMessage() {
                if (this.inputMessage.trim() !== '') {
                    const message = {
                        "content": this.inputMessage.trim(),
                        "type": "text",
                        "toUser": this.toUser,
                        "fromUser": this.fromUser,
                        "sent": true
                    };
                    // 发送消息到WebSocket服务器
                    this.websocket.send(JSON.stringify(message));

                    // 清空输入框
                    this.inputMessage = '';
                    this.scrollToBottom();
                }
            },
            setTime() {
                //写一个循环定时器,而且每次执行setTIme方法都会清除上一次的定时器
                let time = 1000*60*5;
                clearInterval(this.timer);
                this.timer = setInterval(() => {
                    time--;
                    if (time <= 0) {
                        clearInterval(this.timer);
                        this.websocket.close();
                        this.fromUserMsg = [];
                        this.initUserList();
                    }
                }, 1000*60*5);
            },
            getWebsocket() {
                this.chatToken = sessionStorage.getItem("chatToken");
                console.log(this.chatToken)
                if (this.chatToken === null || this.chatToken === ""){
                    axios({
                        url: '/api/chat/chat/getChatToken',
                        method: 'get',
                    }).then(res => {
                        this.chatToken = res.data;
                        sessionStorage.setItem("chatToken", this.chatToken);
                        this.getWebsocket();
                    })
                    return;
                }
                this.websocket = new WebSocket(`ws://localhost:9012/websocket?username=${this.fromUser}&chatToken=${this.chatToken}`);

                // 监听WebSocket连接事件
                this.websocket.onopen = () => {
                    console.log('WebSocket连接已建立');
                    sessionStorage.removeItem("chatToken");
                };

                // 监听WebSocket消息事件
                this.websocket.onmessage = (event) => {
                    if (event.data === 'pong') {
                        return;
                    }
                    if (event.data === "token错误"){
                        alert("token错误，请重新登录");
                        this.websocket.close();
                        return;
                    }
                    const message = JSON.parse(event.data);
                    console.log(message)
                    if (message.fromUser === this.selectedUser.toUser || message.fromUser === this.memberName){
                        let msg = {source: 'to', content: message.content, type: "text", sent: false}
                        if (message.username === this.toUser) {
                            msg.sent = true;
                        }
                        console.log(msg)
                        this.fromUserMsg.push(msg);
                    }else {
                        this.$message({
                            message: '您有新的消息',
                            type: 'success'
                        });
                        let find = false;
                        this.userList.find(item => {
                            if (item.toUser === message.fromUser){
                                item.unread =1;
                                find = true;
                            }
                        });
                        if (!find){
                            this.userList.push({toUser: message.fromUser, unread: 1})
                        }
                    }
                    this.setTime();
                };

                // 监听WebSocket关闭事件
                this.websocket.onclose = () => {
                    console.log('WebSocket连接已关闭');
                    sessionStorage.removeItem("chatToken");
                };

                // 监听WebSocket错误事件
                this.websocket.onerror = (error) => {
                    alert("连接失败，请刷新页面重试");
                    console.error('WebSocket发生错误:', error);
                    sessionStorage.removeItem("chatToken");
                };
            },
            deleteUser(){
                axios({
                    url: '/api/chat/chat/deleteUser',
                    method: 'post',
                    data: {
                        fromUser: this.fromUser,
                        toUser: this.toUser
                    }
                }).then(res => {
                    sessionStorage.removeItem("chatToken");
                    sessionStorage.removeItem("merchantName");
                    this.initUserList();
                    this.websocket.close();
                    this.fromUserMsg = [];
                    location.reload();
                })
            }
        },
        beforeDestroy() {
            // 关闭WebSocket连接
            this.websocket.close();
        }
    };
</script>

<style>
    .selected {
        color: #00c3ff;
    }

    .chat-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
    }

    .chat-list {
        width: 200px;
        height: 500px;
        background-color: #f2f2f2;
        padding: 20px;
        overflow-y: auto;
    }

    .chat-list ul {
        list-style-type: none;
        padding: 0;
        margin: 0;
    }

    .chat-list li {
        cursor: pointer;
        padding: 10px;
        border-radius: 5px;
        margin-bottom: 10px;
        background-color: #ffffff;
    }

    .chat-window {
        width: 500px;
        height: 540px;
        display: flex;
        flex-direction: column;
    }

    .chat-content {
        flex: 1;
        background-color: #f2f2f2;
        padding: 20px;
        height: 500px;
        overflow-y: auto;
    }

    .chat-content ul {
        list-style-type: none;
        padding: 0;
        margin: 0;
    }

    .message {
        display: flex;
        margin-bottom: 10px;
    }

    .message-content {
        max-width: 300px;
        padding: 10px;
        border-radius: 5px;
        background-color: #ffffff;
    }

    .message-content p {
        margin: 0;
    }

    .message.sent {
        justify-content: flex-end;
    }

    .message.received {
        justify-content: flex-start;
    }

    .chat-input {
        display: flex;
        align-items: center;
        padding: 10px;
    }

    .chat-input input {
        flex: 1;
        padding: 10px;
        border-radius: 5px;
        border: 1px solid #cccccc;
        margin-right: 10px;
    }

    .chat-input button {
        padding: 10px 20px;
        background-color: #4caf50;
        color: #ffffff;
        border: none;
        border-radius: 5px;
        cursor: pointer;
    }

</style>
